package Thread;

public class ThreadDemo4 {

    private static Object locker1 = new Object();
    private static Object locker2 = new Object();
    private static Object locker3 = new Object();

    public static void main(String[] args) throws InterruptedException{
        /**
         * 有三个线程，分别只能打印A，B和C
         * 要求按顺序打印ABC，打印10次
         * 输出示例:
         *  ABC
         *  ABC
         *  ABC
         *  ABC
         *  ABC
         *  ABC
         *  ABC
         *  ABC
         *  ABC
         *  ABC
         * **/

        Thread t1 = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    //给1加锁
                    synchronized (locker1) {
                        locker1.wait();//等待
                    }
                    System.out.print("A");
                    //System.out.println();
                    synchronized (locker2) {
                        locker2.notify();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    synchronized (locker2) {
                        locker2.wait();
                    }
                    System.out.print("B");
                    //System.out.println();
                    synchronized (locker3) {
                        locker3.notify();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t3 = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    synchronized (locker3) {
                        locker3.wait();
                    }
                    System.out.print("C");
                    System.out.println();
                    synchronized (locker1) {
                        locker1.notify();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        //启动
        t1.start();
        t2.start();
        t3.start();

        //睡眠1秒
        Thread.sleep(1000);

        //从线程1启动
        synchronized (locker1) {
            locker1.notify();
        }
    }
}
